/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import service.InterfaceServiceLocal;

/**
 *
 * @author dingnangen
 * @param <T>
 */
public class PageDateModel<T> extends LazyDataModel {

    private QueryStr queryStr;
    private InterfaceServiceLocal<T> iService;
    private HashMap<String, String> param = null;//传入的查询参数
    private List params = null;//缓存查询参数
    private List initparams = null;

    public PageDateModel() {
    }

    public PageDateModel(QueryStr queryStr, InterfaceServiceLocal iService, List initparams) {
        this.queryStr = queryStr;
        this.iService = iService;
        this.initparams = initparams;

    }

    public PageDateModel(String table, InterfaceServiceLocal iService) {
        queryStr = new QueryStr(table, 0);
        this.iService = iService;

    }

//    public PageDateModel(String table, InterfaceServiceLocal iService, HashMap<String, String> param) {
//        queryStr = new QueryStr(table, 0);
//        this.iService = iService;
//        this.param = param;
//    }
    @Override
    public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) {
        //重设查询字符串
        queryStr.setDefault();

        params = new ArrayList();

        //附加限定条件
        addCondition();
//        params = new ArrayList(initparams);
        //过滤 
        for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
            try {
                String filterProperty = it.next().replaceAll("\\s*", "");
                Object filterValue = filters.get(filterProperty);
                System.out.println("filterValue type:" + filterValue.getClass());
                queryStr.addLikeCondition("and", filterProperty);
                if (StringUtils.isNumeric(filterValue.toString().replaceAll("\\s*", ""))) {
                    params.add(Integer.parseInt(filterValue.toString().replaceAll("\\s*", "")));
                } else {
                    params.add("%" + filterValue.toString().replaceAll("\\s*", "") + "%");
                }

            } catch (Exception e) {
                System.out.println(e);
            }
        }

        //排序
        System.out.println("sortField:" + sortField + "##sortOrder:" + sortOrder.toString().substring(0, 3));
        if (sortField != null) {
            queryStr.addorderCondition(sortField, convertSortOrder(sortOrder));
            // str += "order by s." + sortField + " " + sortOrder.toString().substring(0, 3);
        }

        System.out.println("PageDateModel:load:" + queryStr.getQueryList());
        //rowCount
        int dataSize = iService.count(queryStr.getQueryCount(), params);

        this.setRowCount(dataSize);
        //paginate
        if (dataSize > pageSize) {
            try {

                //System.out.println("数目:" + ejbFacade.findRange(new int[]{first, (first + pageSize)}).size());
                return iService.findRange(new int[]{first, (first + pageSize)}, queryStr.getQueryList(), params);

            } catch (IndexOutOfBoundsException e) {
                //System.out.println("数目:" + ejbFacade.findRange(new int[]{first, (first + (dataSize % pageSize))}).size());
                return iService.findRange(new int[]{first, (first + (dataSize % pageSize))}, queryStr.getQueryList(), params);

            }
        } else {
            return iService.findAll(queryStr.getQueryList(), params);
        }
        //return super.load(first, pageSize, sortField, sortOrder, filters); //To change body of generated methods, choose Tools | Templates.
    }

//附加条件
//    private void addCondition() {
//        if (this.param != null) {
//            for (Map.Entry<String, String> e : param.entrySet()) {
//                queryStr.addEqualCondition("and", e.getKey());
//                params.add(e.getValue().replaceAll("\\s*", ""));
//            }
//        }
//    }
    private void addCondition() {
        if (this.initparams != null) {
            for (Object e : initparams) {
                params.add(e);
            }
        }
    }

    private String convertSortOrder(SortOrder sortOrder) {
        String order = null;
        switch (sortOrder) {
            case ASCENDING:
                order = "asc";
                break;
            case DESCENDING:
                order = "desc";
                break;
            case UNSORTED:
                order = null;
                break;
            default:
                throw new AssertionError();
        }
        return order;

    }

    //效验
    protected boolean sqlValidate(String str) {
        str = str.toLowerCase();//统一转为小写
        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|"
                + "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|"
                + "table|from|grant|use|group_concat|column_name|"
                + "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|"
                + "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";//过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (String badStr1 : badStrs) {
            if (str.contains(badStr1)) {
                return false;
            }
        }
        return true;
    }

    public QueryStr getQueryStr() {
        return queryStr;
    }

    public void setQueryStr(QueryStr queryStr) {
        this.queryStr = queryStr;
    }

    @Override
    public Object getRowKey(Object object) {
        return super.getRowKey(object); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Object getRowData(String rowKey) {
        return iService.find(Integer.parseInt(rowKey));
    }

}
